/**
 * @Author: WangHongTao
 * @CreateTime: 2006
 * @Description:
 * @Copyright:  2006 Union Operation Support System.
 */
package org.uoss.core.object;

import java.util.HashMap;

import org.uoss.core.util.ValidationUtil;

public class ObjectFactory {

	private static ObjectFactory factory = null;
	private final static HashMap<String,Object> objectCollections = new HashMap<String,Object>();
	
	private ObjectFactory(){}
	
	/**
	 * Return an instance class
	 * @param <T>
	 * @param clz
	 * @return
	 */
	public static <T> T createClass(Class<T> clz){
		if(clz==null)
			return null;
		return clz.cast(createClass(clz.getName()));
	}
	
	/**
	 * Return an object instance
	 * @param classes
	 * @return
	 */
	public static Object createClass(String className){
		Object o = null;
		if(!ValidationUtil.isEmpty(className)){
			if(objectCollections.size()!=0)
				o = objectCollections.get(className);
			if(o==null){
				if(factory==null)
					factory = new ObjectFactory();
				o = factory.newClass(className);
			}
			if(o!=null)
				objectCollections.put(className,o);
		}
		return o;
	}
	
	/**
	 * create a class instance
	 * @param classLabel
	 * @return
	 */
	private Object newClass(String className){
		Object o = null;
		try{
			Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(className);
			if(clz==null){
				o = Class.forName(className).newInstance();
			}
			else
			{
				o = clz.newInstance();
			}

		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return o;
	}
}
